<template>
  <div class="article-page">
    <van-nav-bar fixed placeholder>
      <template #left>
        <van-tabs
          color="#000"
          title-inactive-color="#aaa"
          line-width="12px"
          @click="onSortClick"
        >
          <van-tab title="推荐"></van-tab>
          <van-tab title="最新"></van-tab>
        </van-tabs>
      </template>
      <template #right>
        <div class="logo">
          <img src="@/assets/logo.png" alt="" />
        </div>
      </template>
    </van-nav-bar>

    <van-list v-model="loading" :finished="finished" @load="onLoad">
      <article-item
        :article="item"
        v-for="item in list"
        :key="item.id"
      ></article-item>
    </van-list>
  </div>
</template>
  
<script>
import { getArticleAPI } from '@/api/article'
import ArticleItem from '@/components/ArticleItem.vue'

export default {
  name: "article-page",
  components: { ArticleItem },
  data () {
    return {
      list: [],
      // 表示 是否正在发送请求,
      loading: false,
      // 是否已经分页完毕了，后端没有下一页数据
      finished: false,
      // 定义一个变量 表示 页码
      current: 0,
      pageTotal: 1,
      // 排序关键字 null | "weight_desc"
      sorter: null,
    }
  },
  methods: {
    async onLoad () {
      // 判断有没有下一页数据
      if (this.current < this.pageTotal) {
        this.current++
        const result = await getArticleAPI({
          current: this.current,
          sorter: this.sorter,
        })
        console.log(result)
        // 接口返回 总页数 设置给 this.pageTotal
        this.pageTotal = result.data.data.pageTotal
        // 追加 合并数组
        this.list = [...this.list, ...result.data.data.rows]
        // 数据请求完毕了，需要将 loadding 设置为false
        this.loading = false
      } else {
        finished = true
      }
    },
    async onSortClick (index) {
      // console.log(index)
      if (index === 0) {
        // 推荐
        this.sorter = null
      } else if (index === 1) {
        // 最新
        this.sorter = "weight_desc"
      }

      // 重置
      // 重置页码
      this.current = 0
      // 重置数组
      this.list = []
      // 重新发送请求
      this.onLoad()
    }
  },
};
</script>
  
<style lang="less" scoped>
.article-page {
  .logo {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    > img {
      width: 64px;
      height: 28px;
      display: block;
      margin-right: 10px;
    }
  }
}
.article-item {
  .head {
    display: flex;
    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      overflow: hidden;
    }
    .con {
      flex: 1;
      overflow: hidden;
      padding-left: 10px;
      p {
        margin: 0;
        line-height: 1.5;
        &.title {
          width: 280px;
        }
        &.other {
          font-size: 10px;
          color: #999;
        }
      }
    }
  }
  .body {
    font-size: 14px;
    color: #666;
    line-height: 1.6;
    margin-top: 10px;
  }
  .foot {
    font-size: 12px;
    color: #999;
    margin-top: 10px;
  }
}
</style>